<!--
  一个简洁的文件上传组件。

  用法：
    <qm-file-upload
      :dataKey="formData.noticeId"
      :editable="true"
      :categories="categories"
      title="附件上传"
      fileSize="20"
      fileType=".jpg,.png,.doc,.docx,.xls,.xlsx,.pdf,.txt,.zip,.rar"
    ></qm-file-upload>

  说明：
    dataKey：业务主键
    title：显示的标题
    editable: 是否可编辑
    fileSize：允许上传的文件最大大小
    fileType：允许上传的文件类型

-->
<template>
  <div class="qm-file-upload">
    <el-button
      type="primary"
      v-if="editable"
      @click="uploadModalVisible = true"
    >{{ textMap.upload || '点击上传' }}</el-button>
    <qm-table
      :data="{ data: fileList }"
      :showPager="false"
      :showOrder="false"
      :showCheckbox="false"
      :showToolbar="false"
    >
      <qm-table-column field="fileName">文件名</qm-table-column>
      <template v-slot:moreBtn="{ row }">
        <el-link
          type="primary"
          :underline="false"
          target="_blank"
          @click="openView(row.attachmentId)"
          :title="textMap.view || '预览'"
          v-if="canView(row)"
        >{{ textMap.view || '预览' }}</el-link>&nbsp;&nbsp;
        <el-link
          type="primary"
          :underline="false"
          target="_blank"
          :href="getDownloadUrl(row.attachmentId)"
          :title="textMap.download || '下载'"
        >{{ textMap.download || '下载' }}</el-link>&nbsp;&nbsp;
        <el-link
          type="primary"
          v-if="editable"
          @click="removeFile(row)"
        >{{ textMap.delete || '删除' }}</el-link>
      </template>
    </qm-table>

    <qm-uploader-modal
      ref="qmUploader"
      :title="title"
      :type="type"
      :fileType="fileType"
      :fileSize="fileSize ? +fileSize : undefined"
      v-model="uploadModalVisible"
      :dataKey="dataKey || 'qm-uploader-temp-data-key'"
      :fileList="fileList"
      @file-success="uploadSuccess"
    ></qm-uploader-modal>
  </div>
</template>

<script>
import QmUploaderModal from "./qm-uploader-modal";
import _ from "lodash";
import request from "@/utils/request";

export default {
  name: "qm-file-upload",
  components: {
    QmUploaderModal,
  },
  props: {
    textMap: {
      type: Object,
      default: () => {
        return {
          upload: "点击上传",
          download: "下载",
          delete: "删除",
          view: "预览",
        };
      },
    },
    type: {
      type: String,
      default: "attach",
    },
    categories: {
      type: Array,
      default: () => [],
    },
    editable: Boolean,
    dataKey: String,
    title: String,
    fileType: String,
    fileSize: Number | String,
    viewType: {
      type: String,
      default: "pdf", //pdf:仅PDF预览、office:OnlyOffice预览、none:不提供预览功能
    },
  },
  data() {
    return {
      uploadModalVisible: false,
      fileList: [],
    };
  },
  watch: {
    dataKey(v) {
      if (v) {
        this.fetchAttachments(v);
      } else {
        this.fileList = [];
      }
    },
  },
  methods: {
    canView(row) {
      if (this.viewType == "pdf") {
        return row.fileName.toLowerCase().endsWith(".pdf");
      } else if (this.viewType == "office") {
        return [
          ".doc",
          ".docm",
          ".docx",
          ".dot",
          ".dotm",
          ".dotx",
          ".epub",
          ".fodt",
          ".htm",
          ".html",
          ".mht",
          ".odt",
          ".ott",
          ".pdf",
          ".rtf",
          ".txt",
          ".djvu",
          ".xps",
          ".wps",
          ".csv",
          ".fods",
          ".ods",
          ".ots",
          ".xls",
          ".xlsm",
          ".xlsx",
          ".xlt",
          ".xltm",
          ".xltx",
          ".et",
          ".fodp",
          ".odp",
          ".otp",
          ".pot",
          ".potm",
          ".potx",
          ".pps",
          ".ppsm",
          ".ppsx",
          ".ppt",
          ".pptm",
          ".pptx",
          ".dps",
        ].includes(row.fileType.toLowerCase());
      } else {
        return false;
      }
    },
    openView(attachmentId) {
      this.$root.openFile(this.viewType, attachmentId);
    },
    uploadSuccess(attachment) {
      this.$emit("uploaded", attachment);
    },
    fetchAttachments(dataKey) {
      if (this.categories.length !== 0) {
        var categories = _.join(this.categories, ",");
      } else {
        var categories = "";
      }
      request({
        url: "/attachment/getAllByDataKey",
        method: "get",
        params: { dataKey: dataKey, categories: categories },
      }).then((r) => {
        this.fileList = r || [];
      });
    },
    getDownloadUrl(attachmentId) {
      return `${process.env.VUE_APP_BASE_API}/attachment/download?attachmentId=${attachmentId}`;
    },
    removeFile(file) {
      request({
        url: "/attachment/remove",
        method: "post",
        data: { attachmentId: file.attachmentId },
      })
        .then((r) => {
          if (r && r.success) {
            let idx = _.findIndex(this.fileList, (item) => {
              return item.attachmentId === file.attachmentId;
            });
            if (idx !== -1) {
              this.fileList.splice(idx, 1);
            }
          } else {
            this.msgError((r || {}).message || "删除失败");
          }
        })
        .catch((e) => {});
    },
  },
  created() {
    if (this.dataKey) {
      this.fetchAttachments(this.dataKey);
    }
  },
};
</script>

<style>
</style>
